package com.cavy.platform.server.domain.job;

import com.cavy.platform.server.domain.message.ContainerExecutedFailMessage;
import com.cavy.platform.server.domain.message.JobMessageSubscribe;
import com.cavy.platform.server.domain.message.StageExecutedErrorMessage;
import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
@Data
public class ErrorJob extends AbstractJobAction {
    protected String message;

    public ErrorJob() {
    }

    public ErrorJob(Job job) {
        super(job);
        this.job.status = JobStatus.ERROR;
    }

    @JobMessageSubscribe
    public void containerExecutedFail(ContainerExecutedFailMessage message) {
        JobContainer container = getContainer(message.getStageName(), message.getIndex());
        container.setStatus(JobStageStatus.ERROR);
        if (container.isAllowFailure()) {
            this.job.status = JobStatus.RUNNING;
        }
        save(this);
        sendJob();
        removeSubscribe();
    }

    @JobMessageSubscribe
    public void stageExecutedError(StageExecutedErrorMessage message) {
        JobStage stage = getStage(message.getStageName());
        stage.setStatus(JobStageStatus.ERROR);
        this.message = message.getMessage();
        save(this);
        removeSubscribe();
    }

    @Override
    public void initJobStatus() {
        this.job.status = JobStatus.ERROR;
    }
}
